# @Version : 1.0
# @Author  : wxz
# @File    : exception_handler.py
# @Time    : 2025/5/27 10:25
# @Describe: 描述...
from starlette.exceptions import HTTPException
from starlette.responses import JSONResponse

from config.app_logger import logger


async def validation_exception_handler(request, exc):
    """
    全局的请求参数校验异常
    :param request:
    :param exc:
    :return:
    """
    errors = []
    for error in exc.errors():
        field = ".".join(str(loc) for loc in error['loc'])
        errors.append({
            "field": field,
            "message": error['msg']
        })
    error_msg = f"请求参数错误,{errors}"
    path = request.url.path
    logger.error(f"请求地址:{path}, {error_msg}", exc_info=True)
    return JSONResponse(
        status_code=400,
        content={"code": 400, "message": error_msg, "data": None},
    )


async def global_exception_handler(request, exc):
    """
    全局的HTTP请求异常
    覆盖 HTTPException 错误处理器
    :param request:
    :param exc:
    :return:
    """
    if exc.status_code == 404:
        code = 404
        message = "请求的资源不存在"
    elif exc.status_code == 500:
        code = 500
        message = "系统错误"
    else:
        code = exc.status_code
        message = exc.detail

    return JSONResponse(
        status_code=exc.status_code,
        content={"code": code, "message": message, "data": None},
    )

async def buzz_exception_handler(request, exc):
    """
    自定义业务异常处理器
    :param request:
    :param exc:
    :return:
    """
    path = request.url.path
    logger.error(f"请求地址:{path}, 错误信息: {exc.message}", exc_info=True)
    return JSONResponse(
        status_code=200,
        content={"code": exc.code, "message": exc.message, "data": None},
    )

class BaseAPIException(HTTPException):
    """
    自定义API接口异常类，继承 HTTPException
    模拟：当HTTP请求处理过程中遇到错误时，能够优雅地返回HTTP错误响应给客户端
    当API接口抛出BaseAPIException时，FastAPI会使用对应的exception_handler进行处理
    """
    # HTTP 状态码
    status_code = 200
    # 自定义业务码
    code = -1
    # 自定义业务处理消息
    message = '接口服务异常'

    def __init__(self, message: str = None, status_code: int = None, code: int = None):
        self.message = message or self.message
        self.status_code = status_code or self.status_code
        self.code = code or self.code













